package zcj.stu;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.WebApplicationType;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.GenericApplicationContext;
import org.springframework.stereotype.Component;

import java.awt.image.Kernel;
import java.lang.reflect.Method;

@Configuration
public class C39 {
    public static void main(String[] args) throws Exception{
        SpringApplication spring=new SpringApplication(C39.class);
        spring.addInitializers(applicationContext -> {
             if(applicationContext instanceof GenericApplicationContext){
                 applicationContext=(GenericApplicationContext)applicationContext;
                 ((GenericApplicationContext) applicationContext).registerBean("bean4",bean2.class);
             }
        });
        spring.addListeners(new ApplicationListener<ApplicationEvent>() {
            @Override
            public void onApplicationEvent(ApplicationEvent event) {
                System.out.println("事件为："+event);
            }
        });
        ConfigurableApplicationContext context = spring.run(args);
        System.out.println("1.演示获取Bean definition的源");
        for (String name : context.getBeanDefinitionNames()) {

            System.out.println("name:"+name+" "+"来源:"+ context.getBeanFactory().getBeanDefinition(name).getResourceDescription());
        }
        System.out.println("2.演示推断应用类型");
        Method deduceFromClasspath = WebApplicationType.class.getDeclaredMethod("deduceFromClasspath");
        deduceFromClasspath.setAccessible(true);
        System.out.println("应用类型："+deduceFromClasspath.invoke(null));
        System.out.println("3.演示ApplicationContext初始化器");
        System.out.println("4.演示事件监听器");
        context.close();
    }
    static class bean1{}
    static class bean2{}
    static class bean3{}
    @Bean
    public bean1 bean1(){
        return new bean1();
    }
    @Bean
    public bean2 bean2(){
        return new bean2();
    }
    @Bean
    public bean3 bean3(){
        return new bean3();
    }
    @Bean
    public ServletWebServerFactory webServerFactory(){
        return new TomcatServletWebServerFactory();
    }
}
